<template>
  <el-radio-group :style="{
    width: proxy.$size(width, '100%'),
  }" v-model="keyword" v-bind="{
    ...$attrs,
    disabled: typeof $attrs.disabled === 'function' ? $attrs.disabled(data) : $attrs.disabled
  }" @change="changeBtn">
    <template v-if="isButton">
      <el-radio-button v-for="(item, index) in optionsArr" :key="index" :value="item[valueName]"
        :disabled="item[disabledName]">
        {{ item[labelName] }}
      </el-radio-button>
    </template>
    <template v-else>
      <template v-for="(item, index) in optionsArr" :key="index">
        <el-tooltip effect="dark" :content="item.tooltip" placement="top" :disabled="!!!item.tooltip">
          <el-radio :value="item[valueName]" :disabled="item[disabledName]">
            {{ item[labelName] }}
          </el-radio>
        </el-tooltip>
      </template>
    </template>
  </el-radio-group>
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data: any;
    dataName?: any;
    width?: string | number;
    labelName?: string; //
    valueName?: string; //
    disabledName?: string; //
    options?: any; //
    isButton?: boolean; //

  }>(),
  {
    type: '',
    labelName: 'label',
    valueName: 'value',
    disabledName: 'disabled',
  },
);
const keyword = computed({
  get() {
    if (props.data) {
      return props.dataName ? props.data[props.dataName] : props.data;
    }
    return ''
  },
  set(val) {
    if (props.data) {
      if (props.dataName) {
        props.data[props.dataName] = val
      } else {
        props.data = val;
      }
    }
  },
});
const optionsArr = computed(() => {
  let _arr: any[] = []
  if (Array.isArray(props.options)) {
    _arr = props.options.map((row) => {
      if (typeof row === "object") {
        return row
      } else {
        return {
          label: row,
          value: row,
        }
      }
    })
  } else if (typeof props.options === 'number') {
    _arr = Array.from({ length: props.options }).map((_, idx) => ({
      label: `选项${idx + 1}`,
      value: idx + 1,
    }))
  }
  return _arr
});

const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', val: any, form: any, rows: any[]): void;
}>();
const changeBtn = (val: any) => {
  const rowArr: any = optionsArr.value.filter((el: any) => el[proxy.valueName] === val)
  emit('changeBtn', val, props.data, rowArr)
};


onMounted(() => {
  if ((props.dataName && !props.data[props.dataName]) || (!props.dataName && !props.data)) {
    if (optionsArr.value.length > 0) {
      const _text: any = optionsArr.value[0][props.valueName]
      if (props.dataName) {
        props.data[props.dataName] = _text
      } else {
        props.data = _text;
      }
    }
  }

});
</script>
<style scoped></style>
